//解析颜色标签
const parseColorTags = (text) => {
  if (!text) return ''

  // Regex to find all [COLOR=...]...[/COLOR] tags globally
  const colorRegex = /\[COLOR=(.*?)]([\s\S]*?)\[\/COLOR]/g

  return text.replace(colorRegex, (match, color, content) => {
    // A simple sanitization check to prevent potential CSS injection.
    // It allows rgb, rgba, hex codes, and standard color names.
    const sanitizedColor = /^(rgb|rgba|#|[\w-]+$)/i.test(color.trim()) ? color.trim() : 'inherit'
    return `<span style="color: ${sanitizedColor};">${content}</span>`
  })
}

//解析附件标签
const parseAttachTags = (text) => {
  if (!text) return ''
  // Regex to find [ATTACH...]...[/ATTACH] and capture the ID inside.
  const attachRegex = /\[ATTACH.*?]([\d]+)\[\/ATTACH]/g
  const baseUrl = 'https://dngamer.site/attachments/'

  return text.replace(attachRegex, (match, attachId) => {
    // Construct the full image tag with a class for styling.
    return `<img src="${baseUrl}${attachId}/" alt="附件 ${attachId}" class="parsed-attachment-image" />`
  })
}

//解析粗体标签
const parseBoldTags = (text) => {
  return text.replace(/\[B\](.*?)\[\/B\]/g, '<strong>$1</strong>')
}

// Function to parse [LIST] and [*] tags into <ul><li>
const parseListTags = (text) => {
  // Replace [*] with <li>, handling potential leading newlines
  let processedText = text.replace(/\n?\*\[\*\](.*?)(?=\n?\[\*\]|$)/gs, '<li>$1</li>')
  // Replace [LIST] and [/LIST] with <ul> and </ul>
  processedText = processedText.replace(/\[LIST\]([\s\S]*?)\[\/LIST\]/g, '<ul>$1</ul>')
  processedText = processedText.replace(/\[LIST=\d\]([\s\S]*?)\[\/LIST\]/g, '<ol>$1</ol>') // For ordered lists like [LIST=1]
  return processedText
}

// 处理普通文本（无 quote 部分）
const processTextChunk = (textChunk) => {
  if (!textChunk) return ''
  let processedText = textChunk
  processedText = parseAttachTags(processedText)
  processedText = parseColorTags(processedText)
  processedText = parseBoldTags(processedText)
  processedText = parseListTags(processedText)
  return processedText.trim().replace(/\n/g, '<br>')
}

export const formatReplyMessage = (message) => {
  if (!message) return ''

  // 递归处理 message，支持多个 quote 嵌套和连续
  const processQuotes = (text) => {
    if (!text) return ''
    // 匹配最外层的 [QUOTE] 标签（非贪婪，支持嵌套）
    const quoteRegex = /\[QUOTE="([^,]+),.*?"]([\s\S]*?)\[\/QUOTE\]/g
    let result = ''
    let lastIndex = 0
    let match
    while ((match = quoteRegex.exec(text)) !== null) {
      // 处理 quote 之前的普通文本
      if (match.index > lastIndex) {
        const before = text.slice(lastIndex, match.index)
        result += processTextChunk(before)
      }
      const username = match[1]
      const quotedText = match[2]
      // 递归处理 quotedText（可能有嵌套 quote）
      const formattedQuotedText = processQuotes(quotedText)
      result += `
        <blockquote class="reply-quote">
          <div class="reply-quote-header">回复 <strong>${username}</strong>:</div>
          <div class="reply-quote-content">${formattedQuotedText}</div>
        </blockquote>
      `
      lastIndex = quoteRegex.lastIndex
    }
    // 处理最后一个 quote 后的内容
    if (lastIndex < text.length) {
      const after = text.slice(lastIndex)
      result += processTextChunk(after)
    }
    return result
  }

  // 入口：递归处理 message
  const html = processQuotes(message)
  return `<div class="main-reply-content">${html}</div>`
}
